package org.prs.web.servlet;

import com.prs.util.DateUtil;
import com.prs.util.FileUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.prs.model.Photo;
import org.prs.model.User;
import org.prs.persistence.ChildDatabasePersitenceManager;

public class NewPhotoServlet extends HttpServlet {

    private Photo newPhoto = new Photo();
    private ChildDatabasePersitenceManager persistChildPhoto = new ChildDatabasePersitenceManager();
    private String webPath;

    @Override
    public void init(ServletConfig config) {
        webPath = config.getServletContext().getRealPath("/");
    }

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            StringBuilder photoCreationMessage = new StringBuilder();
            HttpSession session = request.getSession(true);
            User loggedUser = (User) session.getAttribute("loggedinuser");
            if (loggedUser == null) {
                response.sendRedirect("index.jsp");
                return;
            } else {
                newPhoto.setCreatorId(loggedUser.getUserId());
                newPhoto.setChildId((Integer) session.getAttribute("currentchildid"));
            }
            newPhoto.setDateCreated(DateUtil.getTodayAsString());


            if (ServletFileUpload.isMultipartContent(request)) {
                // Create a factory for disk-based file items
                FileItemFactory factory = new DiskFileItemFactory();
                // Create a new file upload handler
                ServletFileUpload upload = new ServletFileUpload(factory);
                // Parse the request
                List /* FileItem */ items = upload.parseRequest(request);
                Iterator iterator = items.iterator();
                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();

                    if (item.isFormField()) {
                        //nothing exists here at the moment
                    } else {
                        if (!FileUtil.isAnImage(item.getContentType())) {
                            photoCreationMessage.append("<div id='inputerror'>Uploaded file is not an image</div>");
                            session.setAttribute("photocreationmsg", photoCreationMessage.toString());
                            response.sendRedirect("addPhoto.jsp");
                            return;
                        }
                        if (item.getFieldName().equals("photo")) {
                            
                            newPhoto.setName(FileUtil.getNewPhotoFileName(item.getContentType()));
                            File photoFile = new File(webPath + "photos/" + newPhoto.getChildId());
                            photoFile.mkdirs();
                            File nphotoFile = new File(photoFile.getPath(), FileUtil.getNewPhotoFileName(item.getContentType()));
                            nphotoFile.createNewFile();
                            FileOutputStream photoFileStream = new FileOutputStream(nphotoFile);
                            photoFileStream.write(item.get());
                            photoFileStream.close();
                            newPhoto.setPath("photos/" + newPhoto.getChildId() + "/" + newPhoto.getName());
                        }

                    }
                }
            }


            //remember to save into file system
            boolean inserted = persistChildPhoto.insertPhoto(newPhoto);
            if (inserted) {
                photoCreationMessage.append("<div id='inputerror'>The photo was added successfully</div>");
                session.setAttribute("photocreationmsg", photoCreationMessage.toString());
                response.sendRedirect("addPhoto.jsp");
            }



        } catch (FileUploadException ex) {
            ex.printStackTrace(System.out);
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
